import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Alert,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import request from '@/utils/request';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import AddOrEditStaffs from './addOrEditUser';
import AddOrEditArea from './addOrEditArea'
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ storehouse_management, loading, global }) => ({
  storehouse_management,
  global,
  loading: loading.models.storehouse_management,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      storehouse_management: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        storehouse_management: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'storehouse_management/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'storehouse_management/changeLoaded',
          });
          dispatch({
            type: 'storehouse_management/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'storehouse_management/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'storehouse_management/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'storehouse_management/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      storehouse_management: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>

          <FormItem label="仓库名称">
            {getFieldDecorator('name', {
              initialValue: searchParams.name,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: 'warehouse_edit' }) &&
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              添加仓库
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'storehouse_management/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('添加仓库成功');
        that.setState({
          addModal: false,
        });
        const {
          storehouse_management: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleAddArea = () => {
    const formValues = this.AddAreaForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    request(`/warehouse_areas`, {
      method: 'post',
      data:{
        ...formValues,
        warehouse_id:this.state.editRecord.id
      }
    }).then((response)=> {
      console.log('response', response)
      if(response.status===200){
        message.success('添加区域成功');
        that.setState({
          addAreaModal: false,
        });
        const {
          storehouse_management: { searchParams,selectedRowKeys },
        } = that.props;
        that.handleSearch(searchParams,function() {
          that.props.dispatch({
            type: 'storehouse_management/changeSelectRow',
            payload: selectedRowKeys,
          });
        });
      }
    })
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      username: '',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `storehouse_management/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改仓库成功');
        that.setState({
          editModal: false,
        });
        const {
          storehouse_management: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleEditArea = () => {
    const formValues = this.EditAreaForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    request(`/warehouse_areas/${this.state.editRecord.id}`, {
      method: 'PUT',
      data:{
        ...formValues,
      }
    }).then((response)=> {
      console.log('response', response)
      if(response.status===200){
        message.success('修改区域成功');
        that.setState({
          editAreaModal: false,
        });
        const {
          storehouse_management: { searchParams,selectedRowKeys },
        } = that.props;
        that.handleSearch(searchParams,function() {
          that.props.dispatch({
            type: 'storehouse_management/changeSelectRow',
            payload: selectedRowKeys,
          });
        });
      }
    })
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `storehouse_management/remove`,
      payload: { id },
      callback: () => {
        message.success('删除操作成功');
        const {
          storehouse_management: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDeleteArea = (id) => {
    const that = this;
    request(`/warehouse_areas/${id}`, {
      method: 'DELETE',
    }).then((response)=> {
      console.log('response', response)
      if(response.status===200){
        message.success('删除区域成功');
        const {
          storehouse_management: { searchParams,selectedRowKeys },
        } = that.props;
        that.handleSearch(searchParams,function() {
          that.props.dispatch({
            type: 'storehouse_management/changeSelectRow',
            payload: selectedRowKeys,
          });
        });
      }
    })
  };
  render() {
    const that = this;
    const {
      storehouse_management: { data, loading, tableY, meta, searchParams, selectedRowKeys,warehouse_areas },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            storehouse_management: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '仓库名称',
        width: 120,
        key: 'name',
        frozen: true,
      },
      {
        name: '仓库地址',
        width: 150,
        key: 'address',
      },
      {
        name: '仓库区域个数',
        width: 100,
        key: 'role_nam3223e2',
        formatter: (event) => {
          return event.row.warehouse_areas.length;
        },
      },
      {
        name: '管理员',
        width: 120,
        key: 'administrator_name',
      },

      {
        name: '备注',
        width: 150,
        key: 'remark',
      },
      {
        name: '操作',
        width: 280,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            find(this.permissions, { name: 'warehouse_edit' }) &&
            <Fragment>
              <Button
                type="primary"
                size="small"
                icon="plus"
                onClick={(e) => {
                  this.setState({
                    editRecord: event.row,
                    addAreaModal: true,
                  });
                }
                }
              >添加仓库区域
              </Button>
            </Fragment>
          }
          {
            find(this.permissions, { name: 'warehouse_edit' }) &&
            <Fragment>
              <Button
                type="primary"
                size="small"
                icon="edit"
                onClick={(e) => {
                  e.stopPropagation();
                  this.setState({
                    editRecord: event.row,
                    editModal: true,
                  });
                }
                }
              >编辑
              </Button>
              <Button
                type="danger"
                size="small"
                icon="delete"
                onClick={(e) => {
                  e.stopPropagation();
                  confirm({
                    title: `确定要删除"${event.row.name}"吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.handleDelete(event.row.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
                }
              >删除
              </Button>
            </Fragment>
          }

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW*0.6) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW*0.6 - totalWidth;
    }
    const columns2 = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            storehouse_management: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '仓库区域',
        width: 150,
        key: 'name',
      },
      {
        name: '区域备注',
        width: 150,
        key: 'remark',
      },
      {
        name: '操作',
        width: 240,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>

          {
            find(this.permissions, { name: 'warehouse_edit' }) &&
            <Fragment>
              <Button
                type="primary"
                size="small"
                icon="edit"
                onClick={(e) => {
                  this.setState({
                    editRecord: event.row,
                    editAreaModal: true,
                  });
                }
                }
              >编辑
              </Button>
              <Button
                type="danger"
                size="small"
                icon="delete"
                onClick={(e) => {
                  e.stopPropagation();
                  confirm({
                    title: `确定要删除"${event.row.name}"吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.handleDeleteArea(event.row.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
                }
              >删除
              </Button>
            </Fragment>
          }

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));
    let data2=data.slice(0,3)
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>仓库档案</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <div style={{width:'60%',display:'inline-block',marginRight:'10px'}}>
            <Alert message="仓库" style={{fontWeight:'bold'}} type="info" />
            <ReactDataGrid
              columns={columns}
              rowGetter={i => {
                return { ...data[i], _index: i };
              }}
              rowsCount={data.length}
              minHeight={tableY}
              rowSelection={{
                showCheckbox: false,
                enableShiftSelect: true,
                selectBy: {
                  indexes: selectedRowKeys,
                },
              }}
              onRowClick={
                (row) => {
                  this.props.dispatch({
                    type: 'storehouse_management/changeSelectRow',
                    payload: [row],
                  });
                }
              }

            />
          </div>
          <div style={{width:'calc(40% - 10px)',display:'inline-block'}}>
            <Alert message={`${warehouse_areas.name?warehouse_areas.name+' 仓库区域':'请选择仓库'} `} style={{fontWeight:'bold'}}  type="success" />
            <ReactDataGrid
              columns={columns2}
              rowGetter={i => {
                return { ...warehouse_areas.warehouse_areas[i], _index: i };
              }}
              rowsCount={warehouse_areas.warehouse_areas.length}
              minHeight={tableY}

            />
          </div>
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加供应商"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 : ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditStaffs
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.addAreaModal} modalClass="addAreaModal"
                                title={`添加 "${this.state.editRecord.name}" 区域`}/>}
        destroyOnClose
        visible={this.state.addAreaModal}
        centered
        onOk={this.handleAddArea}
        className="addAreaModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ addAreaModal: false, editRecord: {} });
        }}

      >
        <AddOrEditArea
          wrappedComponentRef={(inst) => this.AddAreaForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editAreaModal} modalClass="editAreaModal"
                                title={`修改 "${this.state.editRecord.name}"`}/>}
        destroyOnClose
        visible={this.state.editAreaModal}
        centered
        onOk={this.handleEditArea}
        className="editAreaModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editAreaModal: false, editRecord: {} });
        }}

      >
        <AddOrEditArea
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditAreaForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
